# Maintainer: Diego Sogari <diego.sogari@gmail.com>

_realname=pdfium
pkgbase=mingw-w64-${_realname}-git
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}-git"
_basever=2729
pkgver=2729.r2908.696fc8b
pkgrel=1
pkgdesc="Chrome’s PDF rendering engine (mingw-w64)"
arch=('any')
url="https://pdfium.googlesource.com/pdfium/"
license=('BSD')
gtestdir=googletest-release-1.7.0
gmockdir=googlemock-release-1.7.0
makedepends=("git" "gyp-git" "python2"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-cmake")
source=("${_realname}::git+https://pdfium.googlesource.com/pdfium.git#branch=chromium/${_basever}"
        "${gtestdir}.tar.gz::https://codeload.github.com/google/googletest/tar.gz/release-1.7.0"
        "${gmockdir}.tar.gz::https://codeload.github.com/google/googlemock/tar.gz/release-1.7.0"
        "${_realname}-${_basever}.patch")
sha256sums=('SKIP'
            'f73a6546fdf9fce9ff93a5015e0333a8af3062a152a9ad6bcb772c96687016cc'
            '3f20b6acb37e5a98e8c4518165711e3e35d47deb6cdb5a4dd4566563b5efd232'
            '743ea5997d9956ed63b0c391aabf1751e7e6c7186432bd21c0e1fe1e4111cd36')

pkgver() {
  cd "${srcdir}/${_realname}"
  printf "%s.r%s.%s" "${_basever}" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}

prepare() {
  cd "${srcdir}/${_realname}"
  mv -f "../${gtestdir}" ./testing/gtest
  mv -f "../${gmockdir}" ./testing/gmock
  patch -Np1 -i "../${_realname}-${_basever}.patch"
}

build() {
  rm -rf "${srcdir}/build-${MINGW_CHOST}"
  mkdir "${srcdir}/build-${MINGW_CHOST}"
  cd "${srcdir}/build-${MINGW_CHOST}"

  # generate CMake scripts
  export GYP_GENERATORS=cmake
  export GYP_DEFINES='pdf_enable_v8=0 pdf_enable_xfa=0'
  /usr/bin/python2 ../${_realname}/build_gyp/gyp_pdfium

  # detect architecture
  [[ ${MINGW_CHOST} == *"x86_64"* ]] && is64=_x64
  cmake_dir=out/Release${is64}

  # fix CMakeLists.txt:
  #   1. don't treat all warnings as errors
  #   2. replace shared library suffix
  sed -e 's/-Werror//g' \
      -e 's/".so"/".dll"/g' -e 's/libpdfium.so/libpdfium.dll/g' \
      -i "../${_realname}/${cmake_dir}/CMakeLists.txt"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"MSYS Makefiles" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "../${_realname}/${cmake_dir}"

  make
}

#check() {
#  cd "${srcdir}/build-${MINGW_CHOST}"
#  cp -f ./pdfium_embeddertests.exe ./pdfium_unittests.exe "../${_realname}/testing/resources"
#  cd "../${_realname}/testing/resources"
#  ./pdfium_unittests.exe
#  ./pdfium_embeddertests.exe
#}

package() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  install -D ./libpdfium.dll "${pkgdir}${MINGW_PREFIX}/bin/libpdfium.dll"
  install -D ./libpdfium.dll.a "${pkgdir}${MINGW_PREFIX}/lib/libpdfium.dll.a"
  install -D ./obj.target/libpdfium_static.a "${pkgdir}${MINGW_PREFIX}/lib/libpdfium_static.a"
  install -d "${pkgdir}${MINGW_PREFIX}/include"
  install "../${_realname}/public/"*.h "${pkgdir}${MINGW_PREFIX}/include"
}
